/* shelltest.c - shelltest, shellproduce, shellconsume */

#include <xinu.h>
#include <mips.h>
#include <string.h>
#include <stdio.h>
#include <wordlist.h>

void shellproduce(void);
void shellconsume(void);
void shellclock(void);
pid32 shellproducerid;		/* ID of shellproducer process	*/
pid32 shellconsumerid;		/* ID of comsumer process	*/
pid32 shellclockid;		/* ID of clock process		*/
pipid32 shell_pipid_test;		/* ID of pipe used		*/
struct pipent *shell_piptr_test;	/* ptr to pipe's table entry	*/
static unsigned char words[2048][5];
char pstring[2048][5];
char cstring[2048][5];
uint32 pcount = 0;
uint32 vacount = 0;
uint32 vecount = 0;
uint32 vicount = 0;
uint32 vocount = 0;
uint32 vucount = 0;

/*--------------------------------------------------------------------------
 *  sehlltest  -  use shell command to test pipe machanism
 *--------------------------------------------------------------------------
 */
void	shelltest(void)
{
	shell_pipid_test = pipcreate();
	shell_piptr_test = &piptab[shell_pipid_test];

	shellproducerid = create(shellproduce, 1024, 20, "shellproducer", 0);
	shellconsumerid = create(shellconsume, 1024, 20, "shellconsumer", 0);
	shellclockid = create(shellclock, 1024, 20, "shellclock", 0);
	pipconnect(shell_pipid_test, shellproducerid, shellconsumerid);
	resume(shellproducerid);
	resume(shellconsumerid);
	resume(shellclockid);
	pipdisconnect(shell_pipid_test);
	pipdelete(shell_pipid_test);
}

void	shellproduce(void) {
		uint32 i,j;
		uint32 seed = 7;
		for(i = 0; i < 2048; i++) {
			for(j = 0; j <5; j++) {
				pstring[i][j] = words[seed][j];
			}
		seed = (seed*81799)%2048;
		}
		for(i = 0;i < 2048;i++) {
			pipwrite(shell_pipid_test, pstring[i], 5, i*5);
			sleepms(100);
			pcount ++;
		}
}

void	shellconsume(void) {
		uint32 i,j;
		
		for(i = 0; i < 2048; i++) {
			for(j = 0; j <5; j++) {
				cstring[i][j] = ' ';
			}
		}

		for(j = 0; j < 2048; j++) {
				pipread(shell_pipid_test, cstring[j], 5, j*5);
				sleepms(100);
				if (cstring[j][0] == 'A') {
					vacount ++;
				}
				if (cstring[j][0] == 'E') {
					vecount ++;
				}
				if (cstring[j][0] == 'I') {
					vicount ++;
				}
				if (cstring[j][0] == 'O') {
					vocount ++;
				}
				if (cstring[j][0] == 'U') {
					vucount ++;
				}		
			}
}

void	shellclock(void) {
	while (1) {
		sleep (5);
		printf("Number of words generated: %d\n", pcount);
		sleep (5);
		printf("Number of words generated: %d\n", pcount);
		printf("Number of words starting with A: %d\n", vacount);
		printf("Number of words starting with E: %d\n", vecount);
		printf("Number of words starting with I: %d\n", vicount);
		printf("Number of words starting with O: %d\n", vocount);
		printf("Number of words starting with U: %d\n", vucount);
	}	
}
